<!--
  组件使用例子：
  <speak ref='speak' @speaking='append2Msgs' :options='entryData' @emojiVisible='onEmojiVisible'/>
  方法说明：
    speaking:为用户点击发送评论或表情事件，参数为封装好的msg
      @param: [object] msg. {
                type: 1,//1为表情，其他值为文本
                path: "value",  表情的图片地址
                text: "value", 消息的文本,格式为“[土豪]”,发送给后台均发送文本，显示时才显示图片
                COMMUNITY_DATE: 'MM-dd',
                COMMUNITY_TIME: 'hh:mm'
              }
    emojiVisible:告诉父组件表情框显示状态
      @param: [boolean] visbile
  props说明：
    options: {
            userCode: '',//用户代码
            objectType: 4,//业务类型  1：人员  2：系统   3：组合  4：比赛  5：产品
            topicCode: '',//当OBJECT_TYPE为3时，填入对应的组合代码  为4时，是比赛ID  为5时，输入产品的代码
            topicName: '',//当OBJECT_TYPE为3时，填入对应的组合名称
          }
    style: gray: 灰色风格；white: 白色风格，默认为白色风格
-->
<template>
  <div class="wrap" :style='{background: options.style}' v-if='showSpeak'>
    <div class="chat-wrap">
      <div type="text" class="chat_textarea" contenteditable="true" @focus='onFocus' ref='chat_textarea' :class='textareaStyle'></div>
        <i class="iconfont icon-yejichaoyuqi" id="chat_icon-btn-wrap" @click='onEmojiVisible(!$store.state.emojiVisible)'></i>
        <button class="chat_btn-send resizeUIEvent" id="chat_btn-send" @click='onSend'>发送</button>
    </div>
    <div class="chat-emoji-container" id="chat-emoji-container">
      <emoji ref='emoji' v-on:clickEmoji='sendEmoji' v-show='$store.state.emojiVisible'></emoji>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .chat-wrap{
    display: flex;
    justify-content: center;
    .chat_textarea{
      flex: 1;
      /*min-height: 45px;*/
      border: solid 1px #dcdcdc;
      margin: 8px;
      border-radius: 5px;
      padding-left: 8px;
      line-height: 27px;
      font-size: 16px;
    }
    .style-gray{
      background-color: white;
    }
    .icon-yejichaoyuqi{
      font-size: 3rem;
      align-self: flex-end;
      // margin-bottom: -2px;
      opacity: 0.6;
    }
    .chat_btn-send{
      min-width: 52px;
      text-align: center;
      background: #43a7ff;
      color: #fff;
      align-self: flex-end;
      padding-top: 6px;
      padding-bottom: 4px;
      border-radius: 14px;
      border: none;
      margin: 8px;
      font-size: 1.2rem;
    }
  }

</style>

<script>
import Emoji from 'components/game/comment/Emoji'
import RemoteDAO from 'common/remoteDAO'
import CommonUtil from 'common/common.util'
import isInTalkTime from 'filters/isInTalkTime'

export default {
  components:{Emoji},
  filters:{isInTalkTime},
  props:{
    options:{
      type: Object,
      default: function () {
        // body...
        return {
          userCode: '',//用户代码
          objectType: 4,//业务类型  1：人员  2：系统   3：组合  4：比赛  5：产品
          topicCode: '',//当OBJECT_TYPE为3时，填入对应的组合代码  为4时，是比赛ID  为5时，输入产品的代码
          topicName: '',//当OBJECT_TYPE为3时，填入对应的组合名称
          style: 'white',
        }
      }
    }
  },
  data(){
    return {
      talkTime: [{//评论允许的时间
        b: '09:00:00',//begin
        e: '17:00:00'//end
      }],
      tradeDate: new Date(),//交易日期
      textareaStyle: '',//文本编辑区的style
      showSpeak: false //默认不显示评论输入框
    }
  },
  mounted(){
    if(this.style != 'white'){
      this.textareaStyle = 'style-gray';
    }
    //获取允许评论的时段
    CommonUtil.getTalkTime(data => {
      this.talkTime = data;
    });
    //get trade date
    // RemoteDAO.getTradeDate((resp) => {
    //   if(resp.error == '0') this.tradeDate = new Date(this.transferFormatDate(resp.data.body[0].next_trade_date, '/'));
    // })
    this.checkTime()
  },
  methods:{
    checkTime(){
      // 获取交易日
      RemoteDAO.getTradeDate(response=> {
        if (response.error == "0") {
          // 返回交易日字符串
          this.tradeDate = new Date(this.transferFormatDate(response.data.body[0].next_trade_date, '/'));
          // 获取服务器时间
          RemoteDAO.callGT1008(response=> {
            if (response.error == "0") {
              var nowDate = new Date(this.transferFormatDate(response.data.body.date, '/'));
              var nowTime = CommonUtil.formatTime(response.data.body.time).split(':');
              nowDate.setHours(nowTime[0], nowTime[1], nowTime[2]);
              this.showSpeak = isInTalkTime(nowDate, this.tradeDate, this.talkTime)
            }
          });
        } else {
          this.$store.dispatch('setTip',{text:response.data});
          this.showSpeak = false;
        }
      });
    },
    onFocus(){
      this.onEmojiVisible(false);
    },
    onEmojiVisible(visible){
      this.$store.dispatch('setEmojiVisible', visible);
      this.$nextTick(() => {
        this.$emit('emojiVisible', visible);
      });
    },
    /**
     * 将送的消息告诉消息列表
     * @param  {Objecy} msg 消息
     */
    append2Msgs(msg){
      this.$emit('speaking', msg);
    },
    /**
     * 发送表情
     * @param  {object} e {
        type: 1,
        path: "value",  表情的图片地址
        text: "value", 消息的文本,格式为“[土豪]”,发送给后台均发送文本，显示时才显示图片
      }
     */
    sendEmoji(e){
      this.onEmojiVisible(false)
      let msg = {};
      Object.assign(msg, e);
      msg.isSending = true;
      msg.failed = false;
      this.sendMsg(msg, false);
    },
    onSend(){
      let text = this.$refs.chat_textarea.innerText;
      this.$refs.chat_textarea.innerText = '';
      this.$refs.chat_textarea.blur()
      if(text.length <= 0) return;
      let msg = {
        type: 0,
        path: null,
        text: text
      }
      this.sendMsg(msg, false);
    },
    /**
    * msg:{
        type: 0-text,1-牛牛表情
        path: "value",  表情的图片地址
        text: "value", 消息的文本
        isSending: false,
        failed: false,
      }
    * @param reSend 是否为重新发送
    */
    sendMsg(msg, reSend){
      if(msg == undefined || msg == null || msg == '')return;
      msg.isSending = true;
      msg.failed = false;
      RemoteDAO.callGT1008((resp) => {//获取当前时间
        let curDate, time;
        if(resp.error == '0'){
          curDate = new Date(this.transferFormatDate(resp.data.body.date, '/'));
          time = this.formatTime(resp.data.body.time).split(':');
          curDate.setHours(time[0], time[1], time[2]);
        }else{
          curDate = new Date();
        }
        msg = this.setMsgDate(msg, curDate);
        if(!reSend){//非重新发送的消息，需要进行编码，需要加入到msgs中
          msg.text = escape(msg.text).replace(/\%u/g, '\\u');
          this.append2Msgs(msg);
        }
        if(isInTalkTime(curDate, this.tradeDate, this.talkTime)){//在聊天允许的时间段内
          let params = {
            userCode : this.options.userCode,
            actionType : '00',
            businType : 'NRNG',
            communityType : '1',
            objectType : this.options.objectType,
            relationUserCode : '',
            relationUserName : '',
            beginDate : '',
            endDate : '',
            communityContent : msg.text,
            topicCode : this.options.topicCode,
            topicName : this.options.topicName,
            serialNo : ''
          };
          RemoteDAO.callUC12008306(params, (resp) =>{
            msg.isSending = false;
            if(resp.error != '0'){
              msg.failed = true;
              this.$store.dispatch('setTip', {text: resp.data});
            }
          });
        }else{//不在允许的时段
          this.allowChat = false;
          msg.isSending = false;
          msg.failed = true;
          if(this.talkTime.length == 2)
            this.$store.dispatch('setTip', {text:'评论时段为交易日的'+this.talkTime[0].b +'-' + this.talkTime[0].e + '，' + this.talkTime[1].b+'-' + this.talkTime[1].e});
          else if(this.talkTime.length == 1){
            this.$store.dispatch('setTip', {text:'评论时段为交易日的'+this.talkTime[0].b +'-' + this.talkTime[0].e });
          }
        }
      });
    },
    /**
     * 设置消息的日期时间
     * @param {[type]} msg     [description]
     * @param {[type]} curDate [description]
     */
    setMsgDate(msg, curDate){
      var month = curDate.getMonth() + 1;
      var date = curDate.getDate();
      msg['COMMUNITY_DATE'] = (month > 9 ? month : '0'+month) + '-' + (date > 9 ? date : '0'+date);
      var hours = curDate.getHours();
      var minu = curDate.getMinutes();
      msg['COMMUNITY_TIME'] = (hours > 9 ? hours : '0'+hours) + ':' + (minu > 9 ? minu : '0'+minu);
      return msg;
    },
    /**
     * 利用Emoji的str2Emoji方法，将str转换为包含表情的富文本
     * @param  {[type]} str [description]
     * @return {[type]}     [description]
     */
    str2Emoji(str){
      return this.$refs.emoji.str2Emoji(str);
    },
    formatTime (time) {
      time = time + "";
      if (!isNaN(time) && time.length == 6 &&time.indexOf(".")<0) {
        time = time.replace(/^(\d{2})(\d{2})(\d{2})$/, "$1:$2:$3");
      } else if(!isNaN(time) && time.length == 5 &&time.indexOf(".")<0){
        time = "0"+time;
        time = time.replace(/^(\d{2})(\d{2})(\d{2})$/, "$1:$2:$3");
      }
      return time;
    },
    transferFormatDate (str, separator){
      if(str == undefined || str == null || str.length < 8) return '0000'+separator+'00'+separator+'00';
      str += '';
      var year = str.substring(0,4);
      var month = str.substring(4,6);
      if(month.length <= 0) month = '01';
      var day = str.substring(6,8);
      if(day.length <= 0) day = '01';
      return year+separator+month+separator+day;
    },
  }
}
</script>
